const express = require('express');
const router = express.Router();

// 笔记相关API
function setupNoteRoutes(db) {
    // 获取所有笔记
    router.get('/', (req, res) => {
        db.all('SELECT * FROM notes ORDER BY updated_at DESC', (err, rows) => {
            if (err) {
                res.status(500).json({ error: err.message });
                return;
            }
            // 解析tags字段
            const notes = rows.map(row => ({
                ...row,
                tags: row.tags ? JSON.parse(row.tags) : []
            }));
            res.json(notes);
        });
    });

    // 获取单条笔记
    router.get('/:id', (req, res) => {
        const { id } = req.params;
        db.get('SELECT * FROM notes WHERE id = ?', id, (err, row) => {
            if (err) {
                res.status(500).json({ error: err.message });
                return;
            }
            if (!row) {
                return res.status(404).json({ error: '未找到该笔记' });
            }
            // 解析tags字段
            row.tags = row.tags ? JSON.parse(row.tags) : [];
            res.json(row);
        });
    });

    // 获取最近的笔记
    router.get('/recent', (req, res) => {
        const limit = req.query.limit || 3;
        db.all('SELECT * FROM notes ORDER BY updated_at DESC LIMIT ?', [limit], (err, rows) => {
            if (err) {
                res.status(500).json({ error: err.message });
                return;
            }
            const notes = rows.map(row => ({
                ...row,
                tags: row.tags ? JSON.parse(row.tags) : []
            }));
            res.json(notes);
        });
    });

    // 添加新笔记
    router.post('/', (req, res) => {
        const { title, content, category = '快速笔记', tags = [] } = req.body;
        
        if (!title || !content) {
            return res.status(400).json({ error: '笔记标题和内容不能为空' });
        }

        const sql = 'INSERT INTO notes (title, content, category, tags, created_at, updated_at) VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)';
        db.run(sql, [title, content, category, JSON.stringify(tags)], function(err) {
            if (err) {
                res.status(500).json({ error: err.message });
                return;
            }
            res.json({
                id: this.lastID,
                title,
                content,
                category,
                tags,
                created_at: new Date().toISOString(),
                updated_at: new Date().toISOString()
            });
        });
    });

    // 更新笔记
    router.put('/:id', (req, res) => {
        const { id } = req.params;
        const { title, content, category, tags } = req.body;
        
        // 构建更新字段
        const updateFields = [];
        const params = [];
        
        if (title) {
            updateFields.push('title = ?');
            params.push(title);
        }
        
        if (content) {
            updateFields.push('content = ?');
            params.push(content);
        }
        
        if (category) {
            updateFields.push('category = ?');
            params.push(category);
        }
        
        if (tags !== undefined) {
            updateFields.push('tags = ?');
            params.push(JSON.stringify(tags));
        }
        
        // 总是更新updated_at
        updateFields.push('updated_at = CURRENT_TIMESTAMP');
        
        if (updateFields.length === 1) { // 只更新了updated_at
            return res.status(400).json({ error: '没有提供要更新的字段' });
        }
        
        params.push(id);
        const sql = `UPDATE notes SET ${updateFields.join(', ')} WHERE id = ?`;
        
        db.run(sql, params, function(err) {
            if (err) {
                res.status(500).json({ error: err.message });
                return;
            }
            if (this.changes === 0) {
                return res.status(404).json({ error: '未找到该笔记' });
            }
            res.json({ success: true });
        });
    });

    // 删除笔记
    router.delete('/:id', (req, res) => {
        const { id } = req.params;
        
        db.run('DELETE FROM notes WHERE id = ?', id, function(err) {
            if (err) {
                res.status(500).json({ error: err.message });
                return;
            }
            if (this.changes === 0) {
                return res.status(404).json({ error: '未找到该笔记' });
            }
            res.json({ success: true });
        });
    });

    // 批量更新笔记
    router.post('/batch', (req, res) => {
        const notes = req.body;
        if (!Array.isArray(notes)) {
            return res.status(400).json({ error: '请求体必须是笔记数组' });
        }

        // 开始事务
        db.serialize(() => {
            db.run('BEGIN TRANSACTION');
            
            const stmt = db.prepare('UPDATE notes SET title = ?, content = ?, category = ?, tags = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?');
            
            let hasError = false;
            let errorMessage = '';
            
            notes.forEach(note => {
                if (!hasError) {
                    try {
                        stmt.run(
                            note.title,
                            note.content,
                            note.category,
                            JSON.stringify(note.tags || []),
                            note.id
                        );
                    } catch (err) {
                        hasError = true;
                        errorMessage = err.message;
                    }
                }
            });
            
            stmt.finalize();
            
            if (hasError) {
                db.run('ROLLBACK');
                res.status(500).json({ error: errorMessage });
            } else {
                db.run('COMMIT');
                res.json({ success: true });
            }
        });
    });

    return router;
}

module.exports = setupNoteRoutes;